package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

// SingleHost 单主地址访问
type SingleHost struct {
	http.Handler
	allowedHost string
}

func (s *SingleHost) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Println(r.Host)
	if r.Host == s.allowedHost {
		s.Handler.ServeHTTP(w, r)
	} else {
		w.WriteHeader(403)
	}
}

func myHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("hello world!"))
}

// SingleHostFunc 单主地址访问函数
func SingleHostFunc(handler func(http.ResponseWriter, *http.Request), allowedHost string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Println(r.Host)
		if r.Host == allowedHost {
			handler(w, r)
		} else {
			w.WriteHeader(403)
		}
	})
}

type AppendMiddleware struct {
	http.Handler
}

func (a *AppendMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	a.Handler.ServeHTTP(w, r)
	w.Write([]byte("Hey,this is a AppendMiddleware!"))
}

type ModifierMiddleware struct {
	http.Handler
}

func (m *ModifierMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	rec := httptest.NewRecorder()
	m.Handler.ServeHTTP(rec, r)
	for k, v := range rec.Header() {
		w.Header()[k] = v
	}
	w.Header().Set("go-web-foundation", "vip")
	w.WriteHeader(418)
	w.Write([]byte("Hey,this is a middleware!"))
	w.Write(rec.Body.Bytes())
}

func main() {
	/*
		// 类型方式
		 single := &SingleHost{Handler: http.HandlerFunc(myHandler), allowedHost: "localhost"}
		// single := &SingleHost{Handler: http.HandlerFunc(myHandler), allowedHost: "localhost1"}
		http.ListenAndServe(":80", single)
	*/
	/*	//函数方式
		singleFunc := SingleHostFunc(myHandler, "localhost")
		// singleFunc := SingleHostFunc(myHandler, "localhost1")
		http.ListenAndServe(":80", singleFunc)
	*/

	/*
		appen := &AppendMiddleware{Handler: http.HandlerFunc(myHandler)}
		http.ListenAndServe(":80", appen)
	*/
	mid := &ModifierMiddleware{Handler: http.HandlerFunc(myHandler)}
	http.ListenAndServe(":80", mid)
}
